package com.estore.view;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        while (true) {
            showMenu();
            String input = scanner.nextLine().trim(); // 改为读取整行

            // 检查输入是否为空
            if (input.isEmpty()) {
                System.out.println("输入不能为空，请重新输入！");
                continue;
            }

            // 尝试转换为数字
            int choice;
            try {
                choice = Integer.parseInt(input);
            } catch (NumberFormatException e) {
                System.out.println("请输入数字选项！");
                continue;
            }

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    checkout();
                    break;
                case 99: // 隐藏的管理员选项 - 数据备份
                    backupData();
                    break;
                case 0:
                    exitSystem();
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n===== 欢迎来到商城 =====");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 结算购物车");
        System.out.println("0. 退出系统");
        System.out.print("请输入您的选择: ");
    }

    private void browseProducts() {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            products.forEach(System.out::println);
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        String quantityInput = scanner.nextLine(); // 改为读取整行

        // 检查数量输入
        int quantity;
        try {
            quantity = Integer.parseInt(quantityInput);
        } catch (NumberFormatException e) {
            System.out.println("错误：请输入有效的数字！");
            return;
        }

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车为空，无法结算！");
            return;
        }

        // 检查库存是否足够
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            if (product == null || product.getStock() < entry.getValue()) {
                System.out.println("错误：商品 '" + (product != null ? product.getName() : entry.getKey()) + "' 库存不足或不存在！");
                return;
            }
        }

        // 更新库存
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            productService.updateStock(entry.getKey(), entry.getValue());
        }

        System.out.println("结算成功！感谢您的购买！");
        shoppingCart.clear();
        productService.saveData(); // 结算后保存数据
    }

    /**
     * 退出系统
     */
    private void exitSystem() {
        System.out.println("正在保存数据...");
        productService.saveData(); // 在退出前调用保存数据
        System.out.println("感谢使用，再见！");
        scanner.close();
    }

    /**
     * 任务三：数据备份功能
     */
    private void backupData() {
        System.out.println("\n--- 数据备份 ---");
        try {
            // 使用字节流进行文件备份
            FileInputStream fis = new FileInputStream("products.dat");
            FileOutputStream fos = new FileOutputStream("products.dat.bak");

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            fis.close();
            fos.close();

            System.out.println("数据备份成功！备份文件: products.dat.bak");

        } catch (IOException e) {
            System.err.println("备份失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        ConsoleShop shop = new ConsoleShop();

        // 添加关闭钩子，确保程序异常退出时也能保存数据
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\n程序关闭，正在保存数据...");
            shop.productService.saveData();
        }));

        shop.start();
    }
}